package com.itheima.nio.buffer.demo08;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServerDemo08 {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(7171));
        serverSocketChannel.configureBlocking(false);
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null){
                socketChannel.configureBlocking(false);
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int read = socketChannel.read(byteBuffer);
                while (read > 0){
                    byteBuffer.flip();
                    byte[] bytes = byteBuffer.array();
                    System.out.println(new String(bytes, 0, read, "UTF-8"));
                    byteBuffer.clear();
                    read = socketChannel.read(byteBuffer);
                }
                System.out.println("收到了客户端发送的数据....");
                ByteBuffer byteBuffer1 = ByteBuffer.wrap("收到".getBytes("UTF-8"));
                socketChannel.write(byteBuffer1);
                socketChannel.close();
            }

        }

    }
}
